package com.furnitur.modules.portal.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.furnitur.common.exception.BusinessException;
import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.core.entity.address.Address;
import com.furnitur.core.entity.order.Order;
import com.furnitur.core.entity.order.OrderItem;
import com.furnitur.core.entity.order.OrderStatus;
import com.furnitur.core.entity.product.Furniture;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.order.OrderItemMapper;
import com.furnitur.core.mapper.order.OrderMapper;
import com.furnitur.modules.portal.dto.order.OrderCreateDTO;
import com.furnitur.modules.portal.service.PortalAddressService;
import com.furnitur.modules.portal.service.PortalOrderService;
import com.furnitur.modules.portal.service.PortalProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PortalOrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements PortalOrderService {

    @Autowired
    private PortalAddressService addressService;
    
    @Autowired
    private PortalProductService productService;
    
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional
    public Order createOrder(OrderCreateDTO orderDTO) {
        User currentUser = SecurityUtils.getCurrentUser();
        
        // 获取收货地址
        Address address = addressService.getById(orderDTO.getAddressId());
        if (address == null || !address.getUserId().equals(currentUser.getId())) {
            throw new RuntimeException("收货地址不存在或无权限");
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setUserId(currentUser.getId());
        order.setAddressId(orderDTO.getAddressId());
        order.setStatus(0);  // 待付款
        
        Date now = new Date();
        order.setCreatedAt(now);
        order.setUpdatedAt(now);
        
        // 设置收货信息
        order.setReceiverName(address.getReceiverName());
        order.setReceiverPhone(address.getPhone());
        order.setReceiverAddress(String.format("%s%s%s%s", 
            address.getProvince(), 
            address.getCity(), 
            address.getDistrict(), 
            address.getDetailAddress()));
        
        // 计算总金额并保存订单项
        final BigDecimal[] totalAmount = {BigDecimal.ZERO};
        List<OrderItem> orderItems = orderDTO.getItems().stream().map(item -> {
            Furniture furniture = productService.getById(item.getFurnitureId());
            if (furniture == null || furniture.getStock() < item.getQuantity()) {
                throw new RuntimeException("商品库存不足");
            }
            
            // 扣减库存
            furniture.setStock(furniture.getStock() - item.getQuantity());
            productService.updateById(furniture);
            
            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setFurnitureId(furniture.getId());
            orderItem.setFurnitureName(furniture.getName());
            orderItem.setImageUrl(furniture.getImageUrl());
            orderItem.setPrice(furniture.getPrice());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setSubtotal(furniture.getPrice().multiply(new BigDecimal(item.getQuantity())));
            
            // 设置商家ID
            order.setMerchantId(furniture.getMerchantId());
            
            totalAmount[0] = totalAmount[0].add(orderItem.getSubtotal());
            return orderItem;
        }).collect(Collectors.toList());
        
        order.setTotalAmount(totalAmount[0]);
        save(order);
        
        // 保存订单项
        orderItems.forEach(item -> {
            item.setOrderId(order.getId());
            item.setCreatedAt(now);  // 添加创建时间
            item.setUpdatedAt(now);  // 添加更新时间
            orderItemMapper.insert(item);
        });
        
        return order;
    }

    @Override
    @Transactional
    public void payOrder(String orderNo) {
        Order order = getOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 验证订单所有者
        User currentUser = SecurityUtils.getCurrentUser();
        if (!order.getUserId().equals(currentUser.getId())) {
            throw new RuntimeException("无权限操作此订单");
        }
        
        // 验证订单状态
        if (order.getStatus() != 0) {
            throw new RuntimeException("订单状态不正确");
        }
        
        // 模拟支付过程
        order.setStatus(1);  // 已支付
        order.setUpdatedAt(new Date());
        updateById(order);
    }

    @Override
    public Order getOrderDetail(String orderNo) {
        Order order = getOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 验证订单所有者
        User currentUser = SecurityUtils.getCurrentUser();
        if (!order.getUserId().equals(currentUser.getId())) {
            throw new RuntimeException("无权限查看此订单");
        }
        
        return order;
    }

    @Override
    public Page<Order> getOrderList(Integer pageNum, Integer pageSize, Integer status) {
        // 获取当前用户
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 构建查询条件
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>()
            .eq("user_id", currentUser.getId())
            .orderByDesc("created_at");
            
        // 如果指定了状态,添加状态过滤
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        // 查询订单列表
        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);
        
        // 查询订单项
        orderPage.getRecords().forEach(order -> {
            QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<OrderItem>()
                .eq("order_id", order.getId());
            List<OrderItem> orderItems = orderItemMapper.selectList(itemWrapper);
            order.setOrderItems(orderItems);
        });
        
        return orderPage;
    }

    @Override
    @Transactional
    public void cancelOrder(String orderNo) {
        // 获取当前用户
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 查询订单
        Order order = getOne(new QueryWrapper<Order>()
            .eq("order_no", orderNo)
            .eq("user_id", currentUser.getId()));

        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 验证订单状态
        if (order.getStatus() != 0) {
            throw new RuntimeException("只能取消待付款的订单");
        }

        // 更新订单状态为已取消
        order.setStatus(4);  // 4-已取消
        order.setCancelTime(new Date());
        order.setUpdatedAt(new Date());

        // 保存更新
        updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceipt(String orderNo, Long userId) {
        Order order = lambdaQuery()
            .eq(Order::getOrderNo, orderNo)
            .eq(Order::getUserId, userId)
            .one();
        
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != OrderStatus.SHIPPED.getValue()) {
            throw new BusinessException("订单状态不正确");
        }
        
        order.setStatus(OrderStatus.COMPLETED.getValue());
        order.setCompletionTime(new Date());
        updateById(order);
    }

    private String generateOrderNo() {
        return UUID.randomUUID().toString().replace("-", "");
    }


}